package com.anlu.thread.ta5;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description:
 * @author: Andrew
 * @create: 2019-01-30 17:03
 **/
public class Demo {

    private Map<String,Object> map = new HashMap<>();

    private ReadWriteLock rw1 = new ReentrantReadWriteLock();

    private Lock r = rw1.readLock();
    private Lock w = rw1.writeLock();

    private volatile  boolean isUpdate;

    public void readWrite(){
        r.lock();
        if(isUpdate){
            r.unlock();
            w.lock();
            map.put("xxx","xxx");
            r.lock();
            w.unlock();
        }

        Object obj = map.get("xxx");
        System.out.println(obj);

        r.unlock();
    }

    public Object get(String key){
        r.lock();
        System.out.println(Thread.currentThread().getName() + " 读操作在执行..");
        try {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return map.get(key);
        } finally {
            r.unlock();
            System.out.println(Thread.currentThread().getName() + " 读操执行完毕..");
        }
    }

    public void put(String key, Object value) {
        w.lock();
        System.out.println(Thread.currentThread().getName() + " 写操作在执行..");
        try {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key, value);
        } finally {
            w.unlock();
            System.out.println(Thread.currentThread().getName() + " 写操作执行完毕..");
        }
    }

}

